package com.example.dormitorymanagement.service;

import com.example.dormitorymanagement.exception.ResourceNotFoundException;
import com.example.dormitorymanagement.model.Building;
import com.example.dormitorymanagement.model.Room;
import com.example.dormitorymanagement.model.Room.RoomStatus;
import com.example.dormitorymanagement.repository.BuildingRepository;
import com.example.dormitorymanagement.repository.RoomRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@RequiredArgsConstructor
public class RoomService {

    private final RoomRepository roomRepository;
    private final BuildingRepository buildingRepository;

    @Transactional
    public Room createRoom(Integer buildingId, Room room) {
        Building building = buildingRepository.findById(buildingId)
                .orElseThrow(() -> new ResourceNotFoundException("宿舍楼不存在"));

        if (roomRepository.existsByRoomNumberAndBuilding(room.getRoomNumber(), building)) {
            throw new IllegalArgumentException("该宿舍楼中已存在相同房间号");
        }

        room.setBuilding(building);
        return roomRepository.save(room);
    }

    @Transactional(readOnly = true)
    public List<Room> getAllRoomsByBuilding(Integer buildingId) {
        Building building = buildingRepository.findById(buildingId)
                .orElseThrow(() -> new ResourceNotFoundException("宿舍楼不存在"));
        return roomRepository.findByBuilding(building);
    }

    @Transactional(readOnly = true)
    public Room getRoomById(Integer id) {
        return roomRepository.findById(id)
                .orElseThrow(() -> new ResourceNotFoundException("房间不存在"));
    }

    @Transactional
    public Room updateRoom(Integer id, Room roomDetails) {
        Room room = getRoomById(id);
        room.setRoomNumber(roomDetails.getRoomNumber());
        room.setCapacity(roomDetails.getCapacity());
        room.setStatus(roomDetails.getStatus());
        return roomRepository.save(room);
    }

    @Transactional
    public void deleteRoom(Integer id) {
        Room room = getRoomById(id);
        roomRepository.delete(room);
    }

    @Transactional(readOnly = true)
    public List<Room> getAvailableRooms(Integer buildingId) {
        return roomRepository.findByBuildingIdAndStatus(buildingId, RoomStatus.AVAILABLE);
    }

    @Transactional
    public Room updateRoomStatus(Integer roomId, RoomStatus status) {
        Room room = getRoomById(roomId);
        room.setStatus(status);
        return roomRepository.save(room);
    }
}